package com.linking.controller.filter;

import com.borealis.common.utils.StringUtils;
import com.linking.controller.common.AppIdHolder;
import com.linking.controller.common.LocaleHolder;
import com.linking.controller.configuration.WrappedRequest;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author YaoWeiXin
 * @Date 2019/11/1 11:36
 * @Description 玩家过滤器
 */
@Slf4j
public class FirstFilter extends BaseFilter implements Filter {

  @Override
  public void init(FilterConfig filterConfig) {
    pathList.add("/");
  }


  @Override
  public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain)
      throws IOException, ServletException {
    WrappedRequest request = this.getRequest(sRequest);
    HttpServletResponse response = this.getResponse(sResponse);
    if (this.testInOptions(request, response)) {
      return;
    }
    // url的前缀后面是应用编号
    String appId = "";
    String path = request.getServletPath();
    int prefixIndex = path.indexOf(prefixStr);
    if (prefixIndex >= 0) {
      path = path.substring(prefixStr.length());
      appId = path.split("/")[0];
    }
    // 1、验证应用编号是否为空
    if (StringUtils.isEmpty(appId)) {
      printResult(response, "fail path");
      return;
    }
    AppIdHolder.set(appId);
    // 2、设置语言Holder
    Locale locale;
    String language = request.getHeader("LK_LANGUAGE");
    if (StringUtils.isNotEmpty(language)) {
      locale = Locale.forLanguageTag(language);
    } else {
      locale = Locale.getDefault();
    }
    LocaleHolder.set(locale);
    // 3、执行下一步
    chain.doFilter(request, response);
  }

  @Override
  public void destroy() {
    pathList.clear();
  }
}